import 'package:changxindianzishangwu/cache/local_cache.dart';
import 'package:changxindianzishangwu/dao/login_init_dao.dart';
import 'package:changxindianzishangwu/dao/user_info_dao.dart';
import 'package:changxindianzishangwu/else/lib/common/index.dart';
import 'package:changxindianzishangwu/model/base_model.dart';
import 'package:changxindianzishangwu/model/user_info_model.dart';
import 'package:changxindianzishangwu/model/we_chat_user_info_model.dart';
import 'package:changxindianzishangwu/pages/my/settings/bind_phone_msg_page.dart';
import 'package:changxindianzishangwu/pages/my/settings/bind_phone_page.dart';
import 'package:changxindianzishangwu/pages/my/settings/bind_wx_page.dart';
import 'package:changxindianzishangwu/pages/my/settings/update_pwd_page.dart';
import 'package:changxindianzishangwu/util/app_color.dart';
import 'package:changxindianzishangwu/util/app_string.dart';
import 'package:changxindianzishangwu/util/toast.dart';
import 'package:changxindianzishangwu/util/universal_view.dart';
import 'package:changxindianzishangwu/widget/app_bar.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';
import 'package:fluwx/fluwx.dart' as Fluwx;
import 'package:dio/dio.dart' as dio;

class UserCountSafe extends StatefulWidget {
  UserCountSafe({Key key}) : super(key: key);

  @override
  _UserCountSafeState createState() => _UserCountSafeState();
}

class _UserCountSafeState extends State<UserCountSafe> {
  var sex;
  bool _appleLights;

  bool _wxLights;

  String _phone;
  UserInfo _userinfo;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _userinfo = getUserInfo();
    _phone = _userinfo.phone;
    _appleLights = _userinfo.bindAppid == 1 ? true : false;
    _wxLights = _userinfo.bindWx == 1 ? true : false;
    _initWx();
  }

  BuildContext context;

  @override
  Widget build(BuildContext context) {
    this.context = context;
    return Scaffold(
      appBar: TopAppBar(context, "账号安全"),
      body: Column(
        children: [
          Container(
            color: Colors.white,
            child: Column(
              children: <Widget>[
                _item("绑定手机号", ObjectUtil.isEmptyString(_phone) ? "未绑定" : "已绑定",
                    () {
                  if (ObjectUtil.isEmptyString(_phone)) {
                    _intentBind();
                  } else {
                    Get.to(() => BindPhoneMsgPage());
                  }
                }),
                Offstage(
                    offstage: !GetPlatform.isIOS,
                    child: UniversalView().line()),

                Offstage(
                  offstage: !GetPlatform.isIOS,
                  child: MergeSemantics(
                    child: ListTile(
                      title: Text(
                        'Apple ID',
                        style: TextStyle(fontSize: ScreenUtil().setSp(15)),
                      ),
                      trailing: CupertinoSwitch(
                        activeColor: Color.fromRGBO(0, 220, 169, 1),
                        value: _appleLights,
                        onChanged: (bool value) {
                          _appleLights ? _unBindAppId() : _bindingApple();
                          // setState(() {
                          //   _appleLights = value;
                          // });
                        },
                      ),
                    ),
                  ),
                ),
                UniversalView().line(),
                MergeSemantics(
                  child: ListTile(
                    title: Text(
                      '微信号',
                      style: TextStyle(fontSize: ScreenUtil().setSp(15)),
                    ),
                    trailing: CupertinoSwitch(
                      activeColor: Color.fromRGBO(0, 220, 169, 1),
                      value: _wxLights,
                      onChanged: (bool value) {
                        _wxLights ? _unWechat() : _bindingWechat();

                        // setState(() {
                        //   _wxLights = value;
                        // });
                      },
                    ),
                  ),
                ),

                ///todo 7.29 隐藏微信号
                // Divider(
                //   height: 1,
                //   indent: ScreenUtil().setWidth(10),
                //   color: Color.fromRGBO(248, 248, 248, 1),
                //   thickness: ScreenUtil().setHeight(1),
                // ),

                ///todo 不可用
                // _item("绑定微信号", "已绑定", () {
                //   Get.to(() => BindWxPage());
                // }),
              ],
            ),
          ),
          Container(
              margin: EdgeInsets.only(top: 11),
              color: Colors.white,
              child: _item("修改登录密码", "", () {
                if (ObjectUtil.isEmptyString(getUserInfo().phone)) {
                  toast("请先绑定手机号");
                  return;
                }
                Get.to(() => UpdatePwdPage());
              })),
        ],
      ),
    );
  }

  InkWell _item(String title, String label, Function function) {
    return InkWell(
      onTap: function,
      child: ListTile(
        leading: Text(
          title,
          style: TextStyle(fontSize: ScreenUtil().setSp(15)),
        ),
        title: Container(
          alignment: Alignment.centerRight,
          height: ScreenUtil().setHeight(50),
          width: ScreenUtil().setWidth(50),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(4),
          ),
          child: Text(
            label,
            style: TextStyle(
                fontSize: ScreenUtil().setSp(12),
                color: Color.fromRGBO(153, 153, 153, 1)),
          ),
        ),
        trailing: Icon(Icons.keyboard_arrow_right),
      ),
    );
  }

  void _intentBind() async {
    await Get.to(() => BindPhonePage()).then((value) {
      print('---phone-----${getUserInfo().phone}');
      if (!ObjectUtil.isEmptyString(value) && mounted) {
        setState(() {
          _phone = value;
        });
      }
    });
  }

  getHintDialog(String hint, bool isError, Function function) {
    return CupertinoAlertDialog(
        content: new SingleChildScrollView(
          child: ListBody(
            children: <Widget>[
              Text(
                "提示",
                style:
                    TextStyle(fontSize: 13, color: AppColor.colorDefaultText),
              ),
              Text(
                "$hint",
                style:
                    TextStyle(fontSize: 13, color: AppColor.colorDefaultText),
              ),
            ],
          ),
        ),
        actions: <Widget>[
          CupertinoDialogAction(
            child: Text(
              "取消",
              style: TextStyle(color: AppColor.colorGrey153),
            ),
            onPressed: () {
              Navigator.of(context).pop();
            },
          ),
          CupertinoDialogAction(
            child: Text(
              isError ? "确认" : "知道了",
              style:
                  TextStyle(color: isError ? Colors.red : AppColor.colorTheme),
            ),
            onPressed: function,
          ),
        ]);
  }

  /**
   * 苹果
   */
  void _bindingApple() async {
    EasyLoading.show();
    AuthorizationCredentialAppleID credential =
        await SignInWithApple.getAppleIDCredential(
      scopes: [
        AppleIDAuthorizationScopes.email,
        AppleIDAuthorizationScopes.fullName,
      ],
    );

    if (credential != null) {
      bindUserInfo(credential.identityToken, 3);
    } else {
      toast("获取苹果登录认证信息失败");
      EasyLoading.dismiss();
    }
  }

  _unWechat() {
    if (ObjectUtil.isEmptyString(_phone) && !_appleLights) {
      showCupertinoDialog(
          context: context,
          builder: (context) => getHintDialog(
                  GetPlatform.isIOS
                      ? AppString.bindPhoneHint2
                      : AppString.bindPhoneHint3,
                  false, () {
                Navigator.of(context).pop();
              }));
      return;
    }
    showCupertinoDialog(
        context: context,
        builder: (context) =>
            getHintDialog(AppString.unBindWx, true, () {
              _unBind(2);

              Navigator.of(context).pop();
            }));
  }

  _unBind(type) async{
    EasyLoading.show();

    BaseModel _base = await UserInfoDao.unBind(type);
    EasyLoading.dismiss();

    if (_base.resultCode != 1) {
      return toast("解绑失败：${_base.resultMsg}");
    }
    if (type == 2) {
      _userinfo.bindWx = 0;
      setState(() {
        _wxLights = false;
      });
    }
    if (type == 3) {
      _userinfo.bindAppid = 0;
      setState(() {
        _appleLights = false;
      });
    }
    setUserinfoModel(_userinfo);
  }

  _bindingWechat() async {
    var exist = await Fluwx.isWeChatInstalled;

    if (!exist) {
      toast("请先安装微信");
    }
    if (exist) {
      Fluwx.sendWeChatAuth(
              scope: "snsapi_userinfo", state: "wechat_sdk_demo_test")
          .then((value) {
        print('WX login _result :$value');
      });
    }
  }

  _initWx() async {
    String _result = "";
    Fluwx.weChatResponseEventHandler.listen((data) {
      print('WX login _result errCode:${data.errCode}');
      print('WX login _result errStr:${data.errStr}');
      if (data.errCode == 0) {
        EasyLoading.show();

        Fluwx.WeChatAuthResponse wa = data;
        _result += '  Code:' + wa.code;
        _result += '  country:' + wa.country;
        var code;
        print('WX login _result :$_result');

        setState(() {
          code = wa.code;
          print('WX login code :$code');
          getWeChatAccessToken(code); //通过 code 获取 access_token
        });
      }
    });
    // bool wxResult = await isWeChatInstalled;
    //  setState(() {
    //    print("WX is installed $wxResult");
    //  });
  }

  void getWeChatAccessToken(code) async {
    var url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=";
    url += "${AppString.WX_APP_ID}&secret=${AppString.APP_SECRET}&code=" + code;
    url += "&grant_type=authorization_code";
    print('WX login getWeChatAccessToken url：$url');

    //当第一次登录成功后点击退出再登录时，会报40163的错误
    // 40163 指的是使用同一个code 多次请求获取token
    //解决方法：每次请求的code都不一样，所以我们只需在传code的地方让它刷新即可
    String _result;
    try {
      dio.Response response = await dio.Dio().get(url);
      _result = response.data.toString();
      var data = jsonDecode(_result);
      assert(data is Map);
      var access_token = data['access_token'];
      var openid = data['openid'];
      getWeChatUserInfo(access_token, openid); //获取微信用户信息
    } catch (e) {
      EasyLoading.dismiss();
      toast("微信登录失败：$e");
      print('WX login getWeChatAccessToken error：$e');
    }
  }

  void getWeChatUserInfo(accessToken, openId) async {
    if (accessToken == null) return;
    var url = "https://api.weixin.qq.com/sns/userinfo?access_token=";
    url += accessToken + "&openid=" + openId.toString();
    try {
      dio.Response response = await dio.Dio().get(url);
      String dataStr = response.data.toString();
      print('WX login _userinfo：$dataStr');
      Map<String, dynamic> responseData = jsonDecode(dataStr);
      WeChatUserInfoModel _weChatUserinfo =
          WeChatUserInfoModel.fromJson(responseData);
      bindUserInfo(_weChatUserinfo.openid, 2);
    } catch (e) {
      EasyLoading.dismiss();
      toast("微信登录失败：$e");
      print('WX login _userinfo error：$e');
    }
  }

  _unBindAppId() async {
    if (ObjectUtil.isEmptyString(_phone) && !_wxLights) {
      showCupertinoDialog(
          context: context,
          builder: (context) =>
              getHintDialog(AppString.bindPhoneHint1, false, () {
                Navigator.of(context).pop();
              }));
      return;
    }

    showCupertinoDialog(
        context: context,
        builder: (context) =>
            getHintDialog(AppString.unBindAppID, true, () {
              _unBind(3);

              Navigator.of(context).pop();
            }));

  }

  @override
  void dispose() {
    EasyLoading.dismiss();
    // TODO: implement dispose
    super.dispose();
  }

  void bindUserInfo(applyToken, type) async {
    BaseModel _base = await UserInfoDao.binding(applyToken, type);
    EasyLoading.dismiss();
    if (_base.resultCode != 1) {
      return toast("绑定失败：${_base.resultMsg}");
    }
    if (type == 2) {
      _userinfo.bindWx = 1;
      setState(() {
        _wxLights = true;
      });
    }
    if (type == 3) {
      _userinfo.bindAppid = 1;
      setState(() {
        _appleLights = true;
      });
    }

    setUserinfoModel(_userinfo);
  }
}
